package com.opal.system.service.impl;

import com.opal.consts.WSC;
import com.opal.domain.R;
import com.opal.modules.costReportForm.constant.CRF;
import com.opal.modules.costReportForm.entity.AcMail;
import com.opal.modules.costReportForm.entity.ActivitiUser;
import com.opal.modules.costReportForm.entity.CostReport;
import com.opal.modules.costReportForm.service.CostReportFormService;
import com.opal.system.entity.table.OpalUser;
import com.opal.system.entity.table.activiti.ActHiProcinst;
import com.opal.system.entity.table.activiti.ActHiTaskinst;
import com.opal.system.mapper.mysql.SystemActivitiMapper;
import com.opal.system.service.ActivitiService;
import com.opal.system.service.OpalUserService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ActivitiServiceImpl implements ActivitiService {

    @Autowired
    private SystemActivitiMapper systemActivitiMapper;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private OpalUserService opalUserService;
    @Autowired
    private CostReportFormService costReportForcmService;

    @Override
    public Object completeTheTaskDirectlyService(String taskId) {
        try {
            taskService.complete(taskId);
            return new R(WSC.RESTPONSE_OK, "任务处理完成");
        }catch (Exception e){
            e.printStackTrace();
            return new R(WSC.PRECONDITIONFAILED, "任务处理失败");
        }
    }

    @Override
    public Object deleteProcessService(String procInstId,String cause) {
        try {
            runtimeService.deleteProcessInstance(procInstId,cause);
            return new R(WSC.RESTPONSE_OK,"结束流程成功");
        }catch (Exception e){
            e.printStackTrace();
            return new R(WSC.PRECONDITIONFAILED,"结束流程失败");
        }
    }

    @Override
    public Object queryActHiTaskinstByCostReportService(CostReport costReport, String isNull) {
        List<Map<String, Object>> maps = systemActivitiMapper.queryActHiTaskinstByCostReport(costReport, isNull);
        Map<String,Object> map= new HashMap<>();
        map.put("code",0);
        map.put("msg", "成功");
        map.put("data", maps);
        return  map;
    }

    @Override
    public Object queryActHiProcinstService(ActHiProcinst actHiProcinst) {
        HistoricProcessInstanceQuery hpiq = historyService.createHistoricProcessInstanceQuery();
        if (!StringUtils.isBlank(actHiProcinst.getBusinessKey())){   //业务id
            hpiq.processInstanceBusinessKey(actHiProcinst.getBusinessKey());
        }
        if (!StringUtils.isBlank(actHiProcinst.getProcInstId())){    //实例
            hpiq.processInstanceId(actHiProcinst.getProcInstId());
        }
        if (!StringUtils.isBlank(actHiProcinst.getStartUserId())){     //
            hpiq.startedBy(actHiProcinst.getStartUserId());   //发起人
        }
        if (actHiProcinst.getStartTime() !=null){
            hpiq.startedBefore(actHiProcinst.getStartTime() );  //小于给定的时间
        }
        String endActId = actHiProcinst.getEndActId();
        if (!StringUtils.isBlank(endActId)){
            if(endActId.equals("ok")){
                hpiq.finished();    //只查询流程结束的
            }else {
                hpiq.unfinished(); //只查询流程未结束的
            }
        }
       // hpiq.variableValueLike("BUSINESS_KEY_","YT");
        List<HistoricProcessInstance> list = hpiq.list();
        return list;
    }

    @Override
    public Object queryActHiTaskinstService(ActHiTaskinst actHiTaskinst) {
        HistoricTaskInstanceQuery htiq = historyService.createHistoricTaskInstanceQuery();
        String procInstId = actHiTaskinst.getProcInstId();

        if (!StringUtils.isBlank(procInstId))
             htiq.processInstanceId(procInstId);
        htiq.orderByHistoricTaskInstanceStartTime().desc();//根据开始时间排序
        List<HistoricTaskInstance> list = htiq.list();
        return list;
    }

    @Override
    public Object selectVariableService(String procInstId){
        try{
            Map<String, Object> map = runtimeService.getVariables(procInstId);
            return new R(WSC.RESTPONSE_OK,"查询成功",map);
        }catch (Exception ex) {
            ex.printStackTrace();
            System.out.println(ex.getMessage());
            return new R(WSC.PRECONDITIONFAILED,"查询失败，流程已结束");
        }

    }

    @Override
    public Object updateVariableService(String procInstId, AcMail acMail, ActivitiUser activitiUser,Double grossMarginRate,String saleType) {
        try {
            Map<String, Object> map = runtimeService.getVariables(procInstId);
            AcMail acMailV= (AcMail) map.get("acMail");

            acMailV.setFromMail(acMail.getFromMail());   //发送方邮箱);
            acMailV.setToMail(acMail.getToMail());       //声请人邮箱邮箱
            acMailV.setToMail1(acMail.getToMail1());       //项目经理邮箱
            acMailV.setToMail2(acMail.getToMail2());     // 部门经理看邮箱
            acMailV.setToMail3(acMail.getToMail3());     //总经理邮箱
            acMailV.setToMail4(acMail.getToMail4());     //总裁邮箱);
            acMailV.setNeiXiaoCaiWuMail(acMail.getNeiXiaoCaiWuMail());
            acMailV.setNeiXiaoCaiWuMail2(acMail.getNeiXiaoCaiWuMail2());
            acMailV.setNeiXiaoCaiWuMail3(acMail.getNeiXiaoCaiWuMail3());
            acMailV.setWaiXiaoCaiWuMail(acMail.getWaiXiaoCaiWuMail());
            acMailV.setWaiXiaoCaiWuMail2(acMail.getWaiXiaoCaiWuMail2());
            acMailV.setWaiXiaoCaiWuMail3(acMail.getWaiXiaoCaiWuMail3());

            ActivitiUser activitiUserV = (ActivitiUser) map.get("activitiUser");
            activitiUserV.setSubmitName(activitiUser.getSubmitName());   //提交人
            activitiUserV.setTaskName1(activitiUser.getTaskName1());   //项目经理
            activitiUserV.setTaskName2(activitiUser.getTaskName2());  //部门经理
            activitiUserV.setTaskName3(activitiUser.getTaskName3());   //总经理
            activitiUserV.setTaskName4(activitiUser.getTaskName4());   //总裁
            activitiUserV.setCaiwuCount(activitiUser.getCaiwuCount()); //分配财务人数
            activitiUserV.setWaiXiaoCaiWu(activitiUser.getWaiXiaoCaiWu()); //外销财务
            activitiUserV.setWaiXiaoCaiWu2(activitiUser.getWaiXiaoCaiWu2()); //外销财务二
            activitiUserV.setWaiXiaoCaiWu3(activitiUser.getWaiXiaoCaiWu3());//外销财务三
            activitiUserV.setNeiXiaoCaiWu(activitiUser.getNeiXiaoCaiWu()); //内销财务
            activitiUserV.setNeiXiaoCaiWu2(activitiUser.getWaiXiaoCaiWu2()); //内销财务二
            activitiUserV.setNeiXiaoCaiWu3(activitiUser.getNeiXiaoCaiWu3());     //内销财务三

            //以下设置默认是设置好的，防止偶尔改了流程，旧流程未有值
            if (StringUtils.isBlank(acMailV.getCharset())){//邮箱编码
                acMailV.setCharset("utf-8");
            }
            if (StringUtils.isBlank(acMailV.getSubject())){//审批邮箱的标题
                acMailV.setSubject("你有一份要审批的邮件请查收");
            }
            if (StringUtils.isBlank(acMailV.getrSubject())){//申请人邮箱的标题
                acMailV.setrSubject("成本报告审批结果");
            }
            if (StringUtils.isBlank(acMailV.getCaiWuSubject())){//财务邮箱的标题
                acMailV.setCaiWuSubject("成本报告接收请求");
            }

            //审批人邮箱内容：由于审批人邮箱内容都相同,所以整个审批流程只在项目经理设置了一次，若没值就设置一次
            if (StringUtils.isBlank(acMailV.getHtml())){
                List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInstId).list();
                String businessKey = list.get(0).getBusinessKey();
                CostReport costReport = costReportForcmService.getCostReport(businessKey);
                acMailV.setHtml(CRF.disposeMailContent(costReport));
            }
            //财务邮箱内容：它只在部门经理设置了一次
            if (StringUtils.isBlank(acMailV.getCaiWuHtml())){
                List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInstId).list();
                String businessKey = list.get(0).getBusinessKey();
                CostReport costReport = costReportForcmService.getCostReport(businessKey);
                acMailV.setCaiWuHtml(CRF.disposeMailContentReception(costReport));
            }

            map.put("acMail",acMailV);
            map.put("activitiUser",activitiUserV);
            map.put("grossMarginRate",grossMarginRate);
            map.put("saleType",saleType);

            //设置变量
            runtimeService.setVariables(procInstId,map);
            return new R(WSC.RESTPONSE_OK,"修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return new R(WSC.PRECONDITIONFAILED,"修改失败");
        }
    }

    @Override
    public Object getUserService() {
        List<OpalUser> users = opalUserService.selectAllUserService();
        return users;
    }
}
